<template>
  <div class="container">
    <el-main v-loading="loading" element-loading-text="loading..." style="min-height:120px;padding:0px;overflow:hidden">
      <el-row>
        <el-col>
          <el-radio-group v-model="searchDateType" style="margin:0 20px;" @change="getData">
            <el-radio :label="1">按日期查看</el-radio>
            <el-radio :label="0">按小时查看</el-radio>
          </el-radio-group>
          <date-range-picker
            v-show="searchDateType==1"
            v-model="searchdate"
            type="daterange"
            range-separator="~"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="small"
            shortcuts="E"
            @change="getData" />
          <el-date-picker
            v-show="searchDateType==0"
            v-model="onedate"
            :picker-options="datePickerOptions"
            type="date"
            placeholder="选择日期"
            size="small"
            @change="getData"/>
        </el-col>
      </el-row>
      <el-row :gutter="15" style="margin-top:20px;">
        <el-col :sm="12" :xs="24" class="echart-position">
          <div v-show="compute.activeMemberCount" class="echart-position--tip">
            <p>昨日环比：<span v-show="chain.activeMemberCount>=0">+</span>{{ chain.activeMemberCount }}</p>
            <p>昨日增长率：{{ growthRate.activeMemberCount }}</p>
          </div>
          <div id="activeMemberCount" :style="{width: '100%', height: '390px'}"/>
        </el-col>
        <el-col :sm="12" :xs="24" class="echart-position">
          <div v-show="compute.newChildCount" class="echart-position--tip">
            <p>昨日环比：<span v-show="chain.newChildCount>=0">+</span>{{ chain.newChildCount }}</p>
            <p>昨日增长率：{{ growthRate.newChildCount }}</p>
          </div>
          <div id="newChildCount" :style="{width: '100%', height: '390px'}"/>
        </el-col>
      </el-row>
      <el-row style="margin-top:20px;">
        <el-col :sm="12" :xs="24" class="echart-position">
          <div v-show="compute.newMemberCount" class="echart-position--tip">
            <p>昨日环比：<span v-show="chain.newMemberCount>=0">+</span>{{ chain.newMemberCount }}</p>
            <p>昨日增长率：{{ growthRate.newMemberCount }}</p>
          </div>
          <div id="newMemberCount" :style="{width: '100%', height: '380px'}"/>
        </el-col>
        <el-col :sm="12" :xs="24">
          <div/>
        </el-col>
      </el-row>
    </el-main>
  </div>
</template>
<script>
import { getActiveNewRelationData } from '@/api/activity-anomaly-analysis.js';
import { dateShortcutKeyJS } from './../mixins/common.js';
import timeUtils from '@/utils/timeHandle.js';
import textFormatting from '@/utils/textFormatting.js';
import echarts from 'echarts';
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      loading: false,
      searchdate: [
        timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        timeUtils.timeHandle(new Date().getTime(), 'date')
      ],
      onedate: timeUtils.timeHandle(new Date().getTime(), 'date'),
      searchDateType: 1,
      queryList: {
        dateType: 1,
        startTime: timeUtils.timeHandle(
          new Date().getTime() - 3600 * 1000 * 24 * 6,
          'date'
        ),
        endTime: timeUtils.timeHandle(new Date().getTime(), 'date')
      },
      Yesterday: textFormatting.getNextDate(new Date(), -1),
      beforeYesterday: textFormatting.getNextDate(new Date(), -2),
      compute: {
        newMemberCount: false,
        activeMemberCount: false,
        newChildCount: false
      },
      chain: {
        newMemberCount: 0,
        activeMemberCount: 0,
        newChildCount: 0
      },
      growthRate: {
        newMemberCount: '',
        activeMemberCount: '',
        newChildCount: ''
      },
      canvas: {
        newMemberCount: null,
        activeMemberCount: null,
        newChildCount: null
      },
      list: {
        newMemberCount: [],
        activeMemberCount: [],
        newChildCount: []
      },
      backHistroy: {
        newMemberCount: {},
        activeMemberCount: {},
        newChildCount: {}
      },
      timeBar: {
        newMemberCount: [],
        activeMemberCount: [],
        newChildCount: []
      },
      title: {
        newMemberCount: '新增会员实时分布情况',
        activeMemberCount: '活跃会员实时分布情况',
        newChildCount: '新增徒弟实时分布情况'
      },
      dateType: {
        newMemberCount: 1,
        activeMemberCount: 1,
        newChildCount: 1
      },
      axis: {
        newMemberCount: '新增会员(位)',
        activeMemberCount: '活跃会员(位)',
        newChildCount: '新增徒弟(位)'
      }
    };
  },
  mounted() {
    this.backHistroy = {
      newMemberCount: { ...this.queryList },
      activeMemberCount: { ...this.queryList },
      newChildCount: { ...this.queryList }
    };
    window.addEventListener('resize', () => {
      Object.keys(this.canvas).forEach(item => {
        this.canvas[item].resize();
      });
    });
    this.getCanvasData('all');
  },
  methods: {
    // 获取页面数据
    getCanvasData(dataType) {
      this.loading = true;
      getActiveNewRelationData(this.queryList)
        .then(result => {
          if (result.code == 200) {
            if (result.data.length === 0) {
              this.$message.info(
                `${this.queryList.startTime} ~ ${
                  this.queryList.endTime
                } 时间段暂无数据`
              );
              // 还原上级数据 请写代码
              this.queryList = { ...this.backHistroy[dataType] };
              this.dateType[dataType] = 1;
              return false;
            }
            const { data } = result;
            let YesterdayCount = 0;
            let beforeYesterdayCount = 0;

            // 时间轴赋值
            Object.keys(this.timeBar).forEach(item => {
              this.timeBar[item] = data.map(dateItem => dateItem.date);
            });

            // 图标数据赋值
            Object.keys(this.timeBar).forEach(item => {
              this.list[item] = data.map(listItem => listItem[item]);
            });
            if (dataType === 'all') {
              // 更新所有图表
              Object.keys(this.timeBar).forEach(item => {
                this.initCanvas(item);
                data.forEach(dateItem => {
                  if (dateItem.date == this.Yesterday) {
                    YesterdayCount = dateItem[item];
                  }
                  if (dateItem.date == this.beforeYesterday) {
                    beforeYesterdayCount = dateItem[item];
                  }
                  if (
                    this.timeBar[item].indexOf(this.Yesterday) != -1 &&
                    this.timeBar[item].indexOf(this.beforeYesterday) != -1
                  ) {
                    this.compute[item] = true;
                    this.chain[item] = YesterdayCount - beforeYesterdayCount;
                    this.growthRate[item] =
                      beforeYesterdayCount == 0
                        ? '--'
                        : textFormatting.fomatFloat(
                          (YesterdayCount - beforeYesterdayCount) /
                              beforeYesterdayCount *
                              100,
                          2
                        ) + '%';
                  } else {
                    this.compute[item] = false;
                  }
                });
              });
            } else {
              // 更新指定图表
              this.initCanvas(dataType);
              if (
                this.timeBar[dataType].indexOf(this.Yesterday) != -1 &&
                this.timeBar[dataType].indexOf(this.beforeYesterday) != -1
              ) {
                this.compute[dataType] = true;
              } else {
                this.compute[dataType] = false;
              }
            }
            this.loading = false;
          } else {
            this.$message.error(result.msg);
            this.loading = false;
          }
        })
        .catch(() => {
          this.loading = false;
        });
    },
    initCanvas(canvasType) {
      const self = this;
      this.canvas[canvasType] = echarts.init(
        document.getElementById(canvasType)
      );

      // 绘制图表配置coinCashProduceOp
      const option = {
        title: {
          text: this.title[canvasType],
          subtext: `${
            self.dateType[canvasType] === 0 ? self.queryList.startTime : ''
          }`,
          x: 'center'
        },
        grid: {
          top: '70' // 距上边距
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            animation: false
          }
        },
        toolbox: {
          feature: {
            saveAsImage: {
              title: '下载'
            },
            myBack: {
              // 自定义按钮
              show: self.dateType[canvasType] === 0, // 是否显示
              title: '返回',
              icon:
                'path://M315 232.6L293.8 213 11.6 516.5l21.2 19.6 264.8 284.7 21.2-19.6-251-269.9H897v-28.8H64.1L315 232.6z m641.5 270.5h56v27.1h-56v-27.1z', // 图标
              color: '#C0C4CC',
              onclick: function() {
                self.dateType[canvasType] = 1; // 按日期查询
                self.queryList = self.backHistroy[canvasType];
                self.getCanvasData(canvasType);
              }
            }
          }
        },
        axisPointer: {
          link: { xAxisIndex: 'all' }
        },
        xAxis: [
          {
            type: 'category',
            boundaryGap: false,
            triggerEvent: this.dateType[canvasType] === 1,
            data: this.timeBar[canvasType],
            axisLine: {
              onZero: true,
              lineStyle: {
                color: '#909399'
              }
            }
          }
        ],
        yAxis: {
          type: 'value',
          name: `${self.axis[canvasType]}`,
          axisLine: {
            lineStyle: {
              color: '#909399'
            }
          }
        },
        series: [
          {
            name: this.axis[canvasType],
            type: 'line',
            data: this.list[canvasType],
            hoverAnimation: false,
            symbolSize: 10,
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            },
            markLine: {
              data: [{ type: 'average', name: '平均值' }]
            },
            itemStyle: {
              color: this.$store.state.app.eChartColor[0]
            }
          }
        ]
      };
      this.canvas[canvasType].setOption(option);
      //   设置点击x轴触发
      this.canvas[canvasType].off('click');
      this.canvas[canvasType].on('click', function(params) {
        if (self.dateType[canvasType] == 1) {
          if (
            params.componentType == 'xAxis' ||
            params.componentType == 'series'
          ) {
            // 将上一级数据存储
            self.backHistroy[canvasType] = {
              dateType: 1,
              startTime: timeUtils.timeHandle(self.searchdate[0], 'date'),
              endTime: timeUtils.timeHandle(self.searchdate[1], 'date')
            };
            self.dateType[canvasType] = 0; // 按时间查询
          }

          if (params.componentType == 'xAxis') {
            self.queryList = {
              dateType: 0,
              startTime: params.value,
              endTime: params.value
            };
          } else if (params.componentType == 'series') {
            self.queryList = {
              dateType: 0,
              startTime: params.name,
              endTime: params.name
            };
          }
          self.getCanvasData(canvasType);
        }
      });
    },
    getData() {
      this.queryList.dateType = this.searchDateType;
      const type = this.queryList.dateType;
      if (type === 0 && this.onedate == null) {
        this.$message.info('请选择日期，进行按小时查看');
        return false;
      } else if (type === 1 && this.searchdate == null) {
        this.$message.info('请选择日期，进行按日期查看');
        return false;
      }

      this.queryList = {
        dateType: type,
        startTime:
          type == 1
            ? timeUtils.timeHandle(this.searchdate[0], 'date')
            : timeUtils.timeHandle(this.onedate, 'date'),
        endTime:
          type == 1
            ? timeUtils.timeHandle(this.searchdate[1], 'date')
            : timeUtils.timeHandle(this.onedate, 'date')
      };

      this.dateType = {
        newMemberCount: type,
        activeMemberCount: type,
        newChildCount: type
      };
      this.getCanvasData('all');
    }
  }
};
</script>
<style lang="scss" scoped>
.container {
  padding: 20px;
}
.echart-position {
  position: relative;
  &--tip {
    display: inline-block;
    position: absolute;
    right: 40px;
    top: -8px;
    p {
      color: #909399;
      font-size: 12px;
      line-height: 1.6;
    }
  }
}
</style>
